<template>
  <div class="app-container">
    <div>
      <p class="dialogTitle title">当前地震事件:
        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
        <span v-else>请在地震事件管理中设置当前地震事件</span>
      </p>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" v-show="showSearch">
      <el-form-item label="组长" prop="leader">
        <el-input v-model="queryParams.leader" placeholder="请输入组长" clearable />
      </el-form-item>
      <el-form-item label="调查组名称" prop="teamName">
        <el-input v-model="queryParams.teamName" placeholder="请输入调查组名称" clearable />
      </el-form-item>
      <el-form-item label="创建日期" prop="time">
        <el-date-picker v-model="queryParams.time" value-format="YYYY-MM-DD" type="daterange"
            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" :disabled="!currentEvent" @click="handleAdd">新建</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" stripe>
      <el-table-column label="序号" align="center" width="55">
        <template #default="scope">
          <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调查组编号" align="center" prop="teamCode" show-overflow-tooltip >
        <template #default="scope">
          <span style="color: #107ce1;cursor: pointer;" @click="handleEdit(scope.row)">{{ scope.row.teamCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调查组名称" align="center" prop="teamName" />
      <el-table-column label="组长" align="center" prop="leader" />
      <el-table-column label="组长联系方式" align="center" prop="leaderPhone" />
      <el-table-column label="创建单位" align="center" prop="company" />
      <el-table-column label="创建人" align="center" prop="createUserName" />
      <el-table-column label="创建日期" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleCopy(scope.row)">复制</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
        <el-row style="margin: 20px 0;">
          <el-col :span="12">
            <el-form-item label="调查组编号" prop="teamCode">
              <el-input v-model="form.teamCode" placeholder="请输入调查组编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调查组名称" prop="teamName">
              <el-input v-model="form.teamName" placeholder="请输入调查组名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组长" prop="leader">
              <el-input v-model="form.leader" placeholder="请选择组长" :suffix-icon="MoreFilled" readonly
                @click="selectLeader" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组长联系方式" prop="leaderPhone" required>
              <el-input v-model="form.leaderPhone" placeholder="请输入组长联系方式" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调查组描述" prop="teamDesc">
              <el-input v-model="form.teamDesc" type="textarea" maxlength="500" show-word-limit
                :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入调查组描述" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人单位" prop="company" required>
              <el-input v-model="form.company" placeholder="请输入创建单位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="createUser" required>
              <el-input v-model="form.createUser" placeholder="请输入创建人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime" required>
              <el-input v-model="form.createTime" placeholder="请输入创建时间" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs" type="card">
        <el-tab-pane label="组员" name="first">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" @click="handleAddGrounp">添加组员</el-button>
            </el-col>
          </el-row>
          <el-table :data="form.personnel" stripe>
            <el-table-column label="序号" type="index" align="center" width="55" />
            <el-table-column label="姓名" align="center" prop="personName" />
            <el-table-column label="性别" align="center" prop="gender" />
            <el-table-column label="手机号" align="center" prop="tel" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button type="text" @click="deleteGrounp(scope.row,scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="司机" name="second">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" @click="handleAddDriver">添加司机</el-button>
            </el-col>
          </el-row>
          <el-table :data="form.driver" stripe>
            <el-table-column label="序号" type="index" align="center" width="55" />
            <el-table-column label="姓名" align="center" prop="personName" />
            <el-table-column label="性别" align="center" prop="gender" />
            <el-table-column label="手机号" align="center" prop="tel" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button type="text" @click="deleteDriver(scope.row,scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">保 存</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="typeTitle" v-model="openLeader" width="900px" append-to-body>
      <p></p>
      <el-form ref="selectRef" :model="queryParamsLeader">
        <el-row style="margin: 20px 0;">
          <el-col :span="20">
            <el-form-item label="人员姓名" prop="personName" label-width="80px">
              <el-input v-model="queryParamsLeader.personName" placeholder="请输入人员姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleQuery1" style="float: right;">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table ref="selectMunchRef" :data="leaderList" stripe @selection-change="handleSelectionChange" :row-key="typeTitle.value == '选择司机'?'xvmId':'xpimId'">
        <template v-if="typeTitle == '选择组长'">
          <el-table-column label="单选" width="55px">
            <template #default="scope">
              <el-radio :label="scope.row.xpimId" v-model="selectRadio"
                @click.native.stop.prevent="getCurrentRow(scope.row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" width="55">
            <template #default="scope">
              <span>{{ (queryParamsLeader.page - 1) * queryParamsLeader.rows + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="名字" align="center" prop="personName" />
          <el-table-column label="电话" align="center" prop="tel" />
          <el-table-column label="单位" align="center" prop="unit" />
        </template>
        <template v-else>
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column label="序号" align="center" width="55">
            <template #default="scope">
              <span>{{ (queryParamsLeader.page - 1) * queryParamsLeader.rows + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="名字" align="center" prop="personName" />
          <el-table-column label="电话" align="center" prop="tel" />
          <template v-if="typeTitle != '选择组长'">
            <el-table-column label="所在调查组组长" align="center" prop="leader" />
            <el-table-column label="组长手机号" align="center" prop="leaderPhone" />
          </template>
          <el-table-column label="单位" align="center" prop="unit" />
        </template>
      </el-table>
      <pagination v-show="total1 > 0" :total="total1" v-model:page="queryParamsLeader.page"
        v-model:limit="queryParamsLeader.rows" @pagination="getAllPersonne" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="querySelect" :disabled="JSON.stringify(selectionData) === '{}'"
            v-if="typeTitle == '选择组长'">确
            定</el-button>
          <el-button type="primary" @click="querySelect1" :disabled="multiple" v-else>确
            定</el-button>
          <el-button @click="openLeader = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="surveyManage">
import useEventStore from "@/store/modules/event";
import { getAllList, saveData, getDetail, updateData, getCreateInfo, del, getAllListPerson, getListPerson, getListDriver } from "@/api/fieldWork/surveyManage.js"
import { MoreFilled } from '@element-plus/icons-vue'
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const leaderList = ref([]);
const groupList = ref([]);
const driverList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const total1 = ref(0);
const typeTitle = ref('')
const openLeader = ref(false);
const selectionData = ref({});
const selectRadio = ref('');
const forbidden = ref(true);
const selectionData1 = ref([]);
const selectionData2 = ref([]);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const activeName = ref('first')
const data = reactive({
  queryParams: {
    page: 1,
    rows: 10,
    leader: undefined,
    driverName: undefined,
    teamName: undefined,
    time:undefined,
    startTime: undefined,
    endTime:undefined,
  },
  queryParamsLeader: {
    page: 1,
    rows: 10,
    personName: undefined,
  },
  form: {
  },
  rules: {
    teamCode: [{ required: true, message: "调查组编号不能为空", trigger: "blur" }],
    teamName: [{ required: true, message: "调查组名称不能为空", trigger: "blur" }],
    leader: [{ required: true, message: "组长不能为空", trigger: "change" }],
    leaderPhone: [{ required: true, message: "组长联系方式不能为空", trigger: "change" }],
    company: [{ required: true, message: "创建人单位不能为空", trigger: "change" }],
    createUser: [{ required: true, message: "创建人不能为空", trigger: "change" }],
    createTime: [{ required: true, message: "创建时间不能为空", trigger: "change" }],
  }
})
const { queryParams, queryParamsLeader, form, rules } = toRefs(data)

function getCurrentRow(row) {
  if (!forbidden.value) {
    forbidden.value = true
  }
  if (selectRadio.value) {
    if (selectRadio.value == row.xpimId) {
      selectRadio.value = ''
      forbidden.value = false
      setTimeout(() => {
        forbidden.value = true
      }, 0)
      selectionData.value = {};// 取消勾选就把回传数据清除
      return
    } else {
      forbidden.value = false
      setTimeout(() => {
        forbidden.value = true
      }, 0)
    }
  } else {
    forbidden.value = false
    setTimeout(() => {
      forbidden.value = true
    }, 0)
  }
  selectRadio.value = row.xpimId;
  selectionData.value = row;
}

function selectLeader() {
  typeTitle.value = '选择组长'
  getAllPersonne()
}

function querySelect() {
  if (typeTitle.value == '选择组长') {
    form.value.leader = selectionData.value.personName;
    form.value.leaderPhone = selectionData.value.tel;
    form.value.leaderId = selectionData.value.uuid;
    form.value.teamName = selectionData.value.personName + selectionData.value.tel;
  }
  openLeader.value = false;
}

function querySelect1() {
  if (typeTitle.value == '选择组员') {
    let json = form.value.personnel.concat(selectionData1.value);
    console.log(json,'hebing');
    let newJson = [];
    json.forEach(item=>{
      let flag = true;
      item.type = '组员'
      newJson.forEach(itwm2=>{
        if (item.xpimId == itwm2.xpimId) {flag = false; }
      })
      if(flag){newJson.push(item)}
    })
    form.value.personnel = newJson;
  } else if (typeTitle.value == '选择司机') {
    let json = form.value.driver.concat(selectionData2.value);
    let newJson = [];
    json.forEach(item=>{
      let flag = true;
      item.type = '司机'
      newJson.forEach(itwm2=>{
        if (item.xvmId == itwm2.xvmId) {flag = false; }
      })
      if(flag){newJson.push(item)}
    })
    form.value.driver = newJson;
  }
  openLeader.value = false;
  console.log(form.value);
}

function handleSelectionChange(selection) {
  if (typeTitle.value == '选择组员') {
    multiple.value = !selection.length;
    selectionData1.value = selection;
  } else if (typeTitle.value == '选择司机') {
    multiple.value = !selection.length;
    selectionData2.value = selection;
  } else if (typeTitle.value == '选择组长') {
    multiple.value = false;
    selectionData.value = {};
  }
}

function handleAddGrounp() {
  typeTitle.value = '选择组员'
  getAllPersonne()
}

function handleAddDriver() {
  typeTitle.value = '选择司机'
  getAllPersonne()
}

function getAllPersonne() {
  if (typeTitle.value === '选择组长') {
    getAllList1();
  } else if (typeTitle.value === '选择组员') {
    getAllList2();
  } else if (typeTitle.value === '选择司机') {
    getAllList3();
  }
}

function getAllList1() {
  getAllListPerson({ ...queryParamsLeader.value, xsemId: currentEvent.value.id }).then(res => {
    leaderList.value = res.data.rows ? res.data.rows : [];
    total1.value = res.data.total;
    openLeader.value = true;
    proxy.resetForm("selectRef");
    selectRadio.value = '';
    forbidden.value = false;
    selectionData.value = {};
  })
}

function getAllList2() {
  getListPerson({ ...queryParamsLeader.value, xsemId: currentEvent.value.id }).then(res => {
    leaderList.value = res.data.rows ? res.data.rows : [];
    total1.value = res.data.total;
    openLeader.value = true;
    proxy.resetForm("selectRef");
    proxy.$refs["selectMunchRef"].clearSelection();
    selectionData1.value = [];
  })
}

function getAllList3() {
  getListDriver({ ...queryParamsLeader.value, xsemId: currentEvent.value.id }).then(res => {
    leaderList.value = res.data.rows ? res.data.rows : [];
    total1.value = res.data.total;
    openLeader.value = true;
    proxy.resetForm("selectRef");
    proxy.$refs["selectMunchRef"].clearSelection();
    selectionData2.value = [];
  })
}

function deleteGrounp(row,index){
    form.value.personnel.splice(index,1)
}

function deleteDriver(row,index){
  form.value.driver.splice(index,1)
}

// 新增
function handleAdd() {
  title.value = '新建调查组信息';
  getInfo();
}
function getInfo() {
  getCreateInfo({ xsemId: currentEvent.value.id }).then(res => {
    open.value = true;
    activeName.value = 'first';
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.personnel = [];
    form.value.driver = [];
  })
}
// 编辑
function handleEdit(row) {
  title.value = '编辑调查组信息'
  detail(row.xitId);
}
// 查看
function detail(id) {
  getDetail({ id: id }).then(res => {
    open.value = true;
    activeName.value = 'first';
    proxy.resetForm("addRef");
    form.value = res.data;
  })
}
// 复制
function handleCopy(row) {
  title.value = '新建调查组信息';
  getCreateInfo({ xsemId: currentEvent.value.id }).then(res => {
    open.value = true;
    activeName.value = 'first';
    proxy.resetForm("addRef");
    form.value = {...res.data,...row};
  })
}
// 保存
function save() {
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {
      if (title.value == '新建调查组信息') {
        saveData({ ...form.value, xsemId: currentEvent.value.id }).then(res => {
          proxy.$modal.msgSuccess("新建成功");
          open.value = false;
          getList();
        })
      } else {
        updateData({ ...form.value, xsemId: currentEvent.value.id }).then(res => {
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getList();
        })
      }
    }
  })

}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除该信息，请确认是否要删除？",)
    .then(function () {
      return del(row.xitId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 搜索按钮操作 */
function handleQuery1() {
  queryParamsLeader.value.page = 1;
  getAllPersonne();
}

/** 重置按钮操作 */
function resetQuery() {
  dataList.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 查询数据列表 */
function getList() {
  if (currentEvent.value) {
    loading.value = true;
    const query = {
      ...queryParams.value,
      startTime:queryParams.value.time?queryParams.value.time[0]:undefined,
      endTime:queryParams.value.time?queryParams.value.time[1]:undefined,
      xsemId: currentEvent.value.id
    }
    getAllList(query).then(response => {
      dataList.value = response.data.rows ? response.data.rows : [];
      total.value = response.data.total;
      loading.value = false;
    });
  } else {
    dataList.value = [];
    total.value = 0;
  }
}

onMounted(() => {
  setTimeout(() => {
    getList();
  }, 200)
})
</script>

<style scoped lang="scss">
.title {
  margin: 0 0 20px !important;
}
</style>

